package com.example.music_player

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.music_player.data.AppDatabase
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val registerButton = findViewById<Button>(R.id.btn_register)
        val usernameEditText = findViewById<EditText>(R.id.et_username)
        val passwordEditText = findViewById<EditText>(R.id.et_password)
        val loginButton = findViewById<Button>(R.id.btn_login)
        val userDao = AppDatabase.getDatabase(this).userDao()

        registerButton.setOnClickListener {
            // 跳转到 RegisterActivity
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }

        loginButton.setOnClickListener {
            val username = usernameEditText.text.toString().trim()
            val password = passwordEditText.text.toString().trim()

            // 在协程中查询用户
            lifecycleScope.launch {
                // 检查是否为管理员账号
                if (username == "admin" && password == "admin123") {
                    // 保存当前管理员用户名
                    setCurrentUsername(username)

                    // 跳转到管理员界面
                    val intent = Intent(this@MainActivity, AdminActivity::class.java)
                    startActivity(intent)
                    finish() // 结束当前活动
                } else {
                    // 查询数据库，验证用户
                    val user = userDao.getUser(username, password)

                    if (user != null) {
                        // 保存当前用户的用户名
                        setCurrentUsername(username)

                        // 用户验证通过，跳转到用户界面
                        val intent = Intent(this@MainActivity, UserActivity::class.java)
                        startActivity(intent)
                        finish() // 结束当前活动
                    } else {
                        // 用户名或密码错误
                        Toast.makeText(this@MainActivity, "用户名或密码错误", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    private fun setCurrentUsername(username: String) {
        val sharedPreferences = getSharedPreferences("UserPreferences", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putString("currentUsername", username)
        editor.apply()
    }
}
